from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from .models import AbsentType,AbsentStatusChoices,Absent
from .serializers import AbsentSerializer,AbsentTypeSerializer
from apps.oaauth.serializers import UserSerializer
from .utils import get_responder
from .page import MyModelPagination
#发起考勤(creat)
#处理考勤(update)
#查看自己的考勤列表
#查看下属考勤列表

class AbsentView(viewsets.ModelViewSet):
    queryset = Absent.objects.all()
    serializer_class = AbsentSerializer
    pagination_class = MyModelPagination

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset().order_by('-creat_time')
        person = request.query_params.get('person')
        # 如果person=sub 则显示下属的考勤记录
        if person == 'sub':
            result = queryset.filter(responder=request.user)
        else:
            # 默认是显示自己的考勤记录
            result = queryset.filter(requester=request.user)
        # paginate_queryset方法会做分页的逻辑处理
        page = self.paginate_queryset(result)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data
            # 手动格式化日期字段
            for item in data:
                for field in ['start_time', 'creat_time', 'end_time']:
                    if item.get(field):
                        item[field] = item[field][:10]  # 截取前10位 yyyy-mm-dd
            # get_paginated_response除了返回序列化的数据外，还会返回总数据，以及上一页的数据
            return self.get_paginated_response(data)
        serializer = AbsentSerializer(result, many=True)
        data = serializer.data

        # 手动格式化日期字段
        for item in data:
            for field in ['start_time', 'creat_time', 'end_time']:
                if item.get(field):
                    item[field] = item[field][:10]  # 截取前10位 yyyy-mm-dd
        return Response(data)
    def update(self, request, *args, **kwargs):
        #默认情况下，update方法为全字段更新，这里设置为部分更新
        kwargs['partial'] = True
        return super().update(request, *args, **kwargs)


#请假类型
class AbsentTypeView(APIView):
    def get(self, request):
        queryset = AbsentType.objects.all()
        serializer = AbsentTypeSerializer(queryset, many=True)
        return Response(serializer.data)


#显示审批者
class ResponderView(APIView):
    def get(self, request):
        responder = get_responder(request)
        serializer = UserSerializer(responder)
        return Response(serializer.data)



